package com.cango.student.io.bio;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class DemoServer extends Thread {
    private ServerSocket serverSocket;

    public int getPort() {
        return serverSocket.getLocalPort();
    }

    public void run() {
        try {
            // 启动serversocket，端口0代表自动绑定一个空闲端口
            serverSocket = new ServerSocket(0);
            Executor executor = Executors.newFixedThreadPool(8);
            while (true) {
                // 调用accept方法，阻塞等待客户端连接
                Socket socket = serverSocket.accept();
                RequestHandler requestHandler = new RequestHandler(socket);
//                requestHandler.start();
                executor.execute(requestHandler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        DemoServer server = new DemoServer();
        server.start();
        // 利用socket模拟了一个简单客户端，只进行连接，读取，打印
        try (Socket client = new Socket(InetAddress.getLocalHost(), server.getPort())) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(client.getInputStream())));
            bufferedReader.lines().forEach(s -> System.out.println(s));
        }
    }

    // 简化实现，不做读取，直接发送文字


    class RequestHandler extends Thread {
        private Socket socket;

        RequestHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (OutputStream out = new BufferedOutputStream(socket.getOutputStream())) {
                out.write("你好 ".getBytes());
                out.write("\r\n".getBytes());
                out.flush();
                out.write("hello world".getBytes());
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
//            try (PrintWriter out = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()))) {
//                out.print("hello world 你好");
//                out.flush();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            try (OutputStream o = socket.getOutputStream()) {
//                o.write(new String("hello world OutputStream 你好").getBytes());
//                o.flush();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }
    }
}
